package cn.edu.niit.servlet;

import cn.edu.niit.service.BookService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "StoreBookServlet", urlPatterns = "/book/store")
public class StoreBookServlet extends HttpServlet {

    private BookService bookService = new BookService();

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp) throws ServletException, IOException {

        //1. 取参（req当前的页码, 每页的数量, 搜索）
//        String paramJson = IOUtils.toString(
//                req.getInputStream(), "UTF-8");
//        HashMap<String, Object> parseObject =
//                JSON.parseObject(paramJson,
//                        HashMap.class);
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                params.put(entry.getKey(), entry.getValue()[0]);
            }
        }
        String username = (String) req.getSession().getAttribute("id");
        String bookId = (String) params.get("id");

        String message = bookService.storeBook(username, bookId);

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        if (message.equals("借阅成功")) {
            dataMap.put("data", "1");
            resultMap.put("results", dataMap);
            resultMap.put("errorNo", "0");
        }else {
            resultMap.put("errorInfo", "收藏失败，请重试！");
            resultMap.put("results", dataMap);
            resultMap.put("errorNo", "1");
        }

        resp.getWriter().print(JSONObject.toJSON(resultMap).toString());

    }
}
